package com.cn.wanxi.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.session.SessionManagementFilter;

/**
 * @ClassName WebSecurityConfig
 * @Description web 安全配置
 * @Author JiJiang
 * @Date 2022/9/26 15:07
 * @Version 1.0
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    //这里注入的是自定义的UserDetailsServiceImpl的实例
    @Autowired
    private UserDetailsService userDetailsService;


//    UsernamePasswordAuthenticationFilter

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//        SessionManagementFilter

        // 第一步，我们实现了一个当访问index资源时不需要进行验证。
        http.csrf().and().cors().disable().
                authorizeRequests()
                .antMatchers("/").permitAll()//放行
                .anyRequest().authenticated()
                .and()
                //这个配置是绑定了UsernamePasswordAuthenticationFilter的
                //如果不添加则，不会将UsernamePasswordAuthenticationFilter加入过滤器链
                .formLogin()
//                .loginPage("http://127.0.0.1:8989") //指定登录页面资源位置
//                .loginProcessingUrl("/login") //指定登录逻辑处理路径
//                .successForwardUrl("http://127.0.0.1:8989/html/sercurity/index.hml") //指定登录成功跳转页面
                .and()
                .userDetailsService(userDetailsService); //添加自定义的认证规则
    }


    // 定义负责处理密码匹配的解析器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); //使用BCrypt方法加密，特点：一个明文对应多个密文，且都可与之匹配
//        return NoOpPasswordEncoder.getInstance();//不使用加密
    }


}
